package com.itheima.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class LoggingInterceptor implements Interceptor {

    private long startTime;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        startTime = System.currentTimeMillis();

        // 记录 SQL 执行前的日志
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = ms.getBoundSql(invocation.getArgs()[1]);
        String sql = boundSql.getSql();
        System.out.println("Executing SQL: " + sql);

        // 继续执行原始方法
        Object result = invocation.proceed();

        // 记录 SQL 执行后的日志
        long endTime = System.currentTimeMillis();
        System.out.println("SQL executed in " + (endTime - startTime) + "ms");

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 设置拦截器的属性
    }
}
